package com.hanxiaozhang.no2thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 〈一句话功能简述〉<br>
 * 〈面试题：起三个线程，每个线程执行三次，按顺序轮流执行，输出1-99〉
 *
 * @author hanxinghua
 * @create 2020/1/30
 * @since 1.0.0
 */
public class No1Example {
    static volatile int count = 1;

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(new TestPrint(0, "thread1"));
        executorService.submit(new TestPrint(1, "thread2"));
        executorService.submit(new TestPrint(2, "thread3"));
    }

    static class TestPrint implements Runnable {

        private int number;
        private String threadName;

        public TestPrint(int number, String threadName) {
            this.number = number;
            this.threadName = threadName;
        }

        @Override
        public void run() {
            synchronized (TestPrint.class) {
                while (count < 99) {
                    if (count / 3 % 3 == number) {
                        int j = count;
                        for (int i = j; i < j + 3; i++) {
                            System.out.println(threadName + "|" + count);
                            count++;
                        }
                        TestPrint.class.notifyAll();
                    } else {
                        try {
                            TestPrint.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
